﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NPOI.SS.Formula.Functions;
using S4Store.Models;
using S4Store.Service;
using S4Store.Domain;
using S4Store.Models.Actionplan;
using LX.Core.Utils;

namespace S4Store.Controllers
{
    public class ActionplanController : ReportBaseController
    {
        public ActionplanService ActionplanService { get; set; }
        public ImproveGuideService ImproveGuideService { get; set; }


        public ActionResult Index()
        {
            IndexModel model = new IndexModel();
            QueryModel query = new QueryModel
            {
                Page = 1,
                PageSize = 1000
            };
            switch (CurrentUser.Position)
            {
                case Position.SalesManager:
                    query.Type = Information.InformationType.Sale.ToInt();
                    query.UserId = CurrentUser.Id;
                    break;
                case Position.MarketingManager:
                    query.Type = ImproveGuide.ImproveGuideType.Markting.ToInt();
                    query.UserId = CurrentUser.Id;
                    break;
                case Position.AftersalesManager:
                    query.Type = ImproveGuide.ImproveGuideType.AfterSale.ToInt();
                    query.UserId = CurrentUser.Id;
                    break;
                case Position.SystemManager:
                case Position.StoreManager:
                case Position.GeneralManager:
                    query.Type = null;
                    query.UserId = null;
                    break;
            }

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                if (query.Type != null)
                {
                    querysource = querysource.Where(x => x.PlanTypeValue == query.Type);
                }
                if (query.UserId != null)
                {
                    querysource = querysource.Where(x => x.AppUserId == query.UserId.Value);
                }
                if (query.Status != 0)
                {
                    querysource = querysource.Where(x => x.PlanStatusValue == query.Status);
                }
                querysource = querysource.OrderByDescending(x => x.Id);
                querysource = querysource.Where(o => o.Start.Month == Month.Month || o.End.Month == Month.Month);
                model.Data = querysource.ToList();
            }
            this.InjectReportModel(model);
            model.BarModel.Action = "Index";
            model.BarModel.Controller = "Actionplan";
            model.BarModel.AddView(ReportBarModel.ViewItem.Month);
            return View(model);            
        }


        public ActionResult Query()
        {
            QueryModel query = new QueryModel
            {
                Page = 1,
                PageSize = 20
            };
            return Query(query);
        }

        [HttpPost]
        public ActionResult Query(QueryModel query)
        {
            if (CurrentUser.Position == Position.SalesManager)
            {
                query.Type = Information.InformationType.Sale.ToInt();
                query.UserId = CurrentUser.Id;
            }
            else if (CurrentUser.Position == Position.MarketingManager)
            {
                query.Type = ImproveGuide.ImproveGuideType.Markting.ToInt();
                query.UserId = CurrentUser.Id;
            }
            else if (CurrentUser.Position == Position.AftersalesManager)
            {
                query.Type = ImproveGuide.ImproveGuideType.AfterSale.ToInt();
                query.UserId = CurrentUser.Id;
            }
            else if (CurrentUser.Position == Position.GeneralManager || CurrentUser.Position == Position.StoreManager || CurrentUser.Position == Position.SystemManager)
            {
                query.Type = null;
                query.UserId = null;
            }

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                if (query.Type != null)
                {
                    querysource = querysource.Where(x => x.PlanTypeValue == query.Type);
                }
                if (query.UserId != null)
                {
                    querysource = querysource.Where(x => x.AppUserId == query.UserId.Value);
                } 
                if (query.Status!= 0)
                {
                    querysource = querysource.Where(x => x.PlanStatusValue == query.Status);
                }
                if (!String.IsNullOrWhiteSpace(query.Title))
                {
                    querysource = querysource.Where(x => x.Title.Contains(query.Title));
                }
                int total = querysource.Count();
                querysource = querysource.OrderByDescending(x => x.Id);
                if (query.Page > 1 && query.PageSize > 0)
                {
                    querysource = querysource.Skip((query.Page - 1) * query.PageSize);
                }
                querysource = querysource.Take(query.PageSize);
                LX.Core.Query.PagedList<Actionplan> data = new LX.Core.Query.PagedList<Actionplan>
                {
                    Data = querysource.ToList(),
                    Page = query.Page,
                    PageSize = query.PageSize,
                    Total = total

                };
                return View(data);
            }
        }

        public ActionResult Detail(int id){
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                var model = querysource.FirstOrDefault(x => x.Id == id);
                t.Commit();
                return View(model);
            }
        }


        public ActionResult Add(int improveId = 0,int rnd=0)
        {
            using (var t=new Transtion())
            {
                t.Inject(ImproveGuideService);
                var addModel = new AddModel();
                var model = ImproveGuideService.GetQuery().FirstOrDefault(o => o.Id == improveId);
                if (model != null)
                {
                    addModel.ImproveGuideModel = model;
                }
                return View(addModel);
            }
           
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult Add(Actionplan model)
        {
            if (CurrentUser.Position == Position.AftersalesManager)
            {
                model.Type = Actionplan.PlanType.AfterSale;
            }
            if (CurrentUser.Position == Position.SalesManager)
            {
                model.Type = Actionplan.PlanType.Sale;
            }
            if (CurrentUser.Position == Position.MarketingManager)
            {
                model.Type = Actionplan.PlanType.Marketing;
            }
            model.AppUserId = CurrentUser.Id;
            
            model.StoreId = CurrentUser.StoreId.Value;
            model.FinishEnd = model.Start.AddDays(-9999);
            model.FinishStart = model.Start.AddDays(-9999);
            model.WriteDate = model.Start.AddDays(-9999);

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                ActionplanService.AddActionplan(model);
                t.Commit();
                return new JsonResult
                {
                    Data = new
                    {
                        success = true
                    }
                };
            }
        }

        public ActionResult Modify(int id)
        {

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                var model = querysource.FirstOrDefault(x => x.Id == id);
                if (model.Status != Actionplan.PlanStatus.Application)
                {
                    return Content("只能删除未批准执行的计划");
                    
                }
                t.Commit();
                return View(model);
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult ModifyBack(Actionplan model)
        {
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                var querysource = ActionplanService.GetQuery();
                var rmodel = querysource.FirstOrDefault(x => x.Id == model.Id);
                rmodel.Title = model.Title;
                rmodel.Start = model.Start;
                rmodel.End = model.End;
                rmodel.Content = model.Content;
                ActionplanService.ModifyActionplan(rmodel);
                t.Commit();
                return new JsonResult
                {
                    Data = new
                    {
                        success = true
                    }
                };
            }

        }

        [HttpPost]
        public JsonResult Delete(List<int> ids)
        {
            if (Helper.ArrayIsEmpty(ids))
            {
                throw new Exception("请选择要删除的项");
            }
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                foreach (var id in ids)
                {
                    ActionplanService.DeleteActionplan(id,CurrentUser);
                }
                t.Commit();
            }
            return new JsonResult
            {
                Data = new
                {
                    success = true,
                    result = "删除成功"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        public JsonResult PZ(int id)
        {
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                
                    var plan = ActionplanService.GetQuery().FirstOrDefault(x => x.Id == id);
                    ActionplanService.ApproveActionplan(plan, CurrentUser);
              
                t.Commit();
            }
            return new JsonResult
            {
                Data = new
                {
                    success = true,
                    result = "执行成功"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        public JsonResult Finish(int id)
        {
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var plan = ActionplanService.GetQuery().FirstOrDefault(x => x.Id == id);
                ActionplanService.FinishActionplan(plan, CurrentUser);

                t.Commit();
            }
            return new JsonResult
            {
                Data = new
                {
                    success = true,
                    result = "执行成功"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        public ActionResult WriteResult(int id,DateTime dt)
        {

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                var model = querysource.FirstOrDefault(x => x.Id == id);
                model.WriteDate = dt;
                //if (model.Status != Actionplan.PlanStatus.Application)
                //{
                //    return Content("已填写过了");
                //}
                //t.Commit();
                return View(model);
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult WriteResult(Actionplan model)
        {
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                var querysource = ActionplanService.GetQuery();
                var rmodel = querysource.FirstOrDefault(x => x.Id == model.Id);
                rmodel.FinishStart = model.FinishStart;
                rmodel.FinishEnd = model.FinishEnd;
                rmodel.Achievement = model.Achievement;
                rmodel.WriteDate = model.WriteDate;
                ActionplanService.WriteResult(rmodel,CurrentUser);
                t.Commit();
                return new JsonResult
                {
                    Data = new
                    {
                        success = true
                    }
                };
            }

        }

        public ActionResult ConfirmResult(int id, DateTime dt)
        {

            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);

                var querysource = ActionplanService.GetQuery();
                var model = querysource.FirstOrDefault(x => x.Id == id);
                //if (model.Status != Actionplan.PlanStatus.Excuted)
                //{
                //    return Content("此计划还没有完成 或 你已经确认");
                //}
                //t.Commit();
                return View(model);
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult ConfirmResult(Actionplan model)
        {
            using (var t = new Transtion())
            {
                t.Inject(ActionplanService);
                var querysource = ActionplanService.GetQuery();
                var rmodel = querysource.FirstOrDefault(x => x.Id == model.Id);
                rmodel.Status = Actionplan.PlanStatus.Finish;
                rmodel.ConfirmInfo = model.ConfirmInfo;
                t.Commit();
                return new JsonResult
                {
                    Data = new
                    {
                        success = true
                    }
                };
            }

        }
    }
}
